package network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Observable;
import java.util.Set;

public class ServerConnection extends Observable implements Runnable {

	private static final int PORT = 1313;
	private static final String HOST = "localhost";
	private BufferedReader in;
	private BufferedWriter out;
	private Set<Netlistener> listeners = new HashSet<Netlistener>();
	private Socket sock;

	public ServerConnection() {
		try {
			sock = new Socket(HOST, PORT);
			
			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
			out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addListener(Netlistener l) {
		listeners.add(l);
	}
	
	@Override
	public void run() {
		try {
			while (true) {
				String str = in.readLine();
			
				Netevent e = new Netevent(str);

				for (Netlistener l: listeners) {
					l.recieve(e);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			close();
		}
		
	}
	private void close() {
		try {
			sock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void send(String str) {
		try {
			out.write(str +"\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
